<?php
namespace app\web\controller;

use app\model\Theme; 

class Group extends Base
{
    public function Group()
    {
global $_G, $_P;
$system = $_G['system'];
$_G['page']['title'] = '团长列表 - ' . $system['sysname'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
	$themeid = Theme::getDefaultThemenew($_G['mpid']);
}
$theme = Theme::getThemeById($themeid);
if(empty($theme['id'])){
	return_msg('还没有创建活动,请联系管理员');
}

$config = 	Theme::getConfig($themeid);
$id = intval($_P['id']);
$do = 'group';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));

if($op == 'delete') {
	db_delete(t_detail, array('uniacid' => $_G['mpid'],'groupid' => $id,'themeid'=>$themeid));
	db_delete(t_group, array('uniacid' => $_G['mpid'],'id' => $id,'themeid'=>$themeid));
	return_msg('删除成功！', $url, 'success');
}

if($op == 'isluck') {
    $isluck = intval($_P['isluck']);
    $state = db_update(t_group, array('isluck' => $isluck), array('uniacid' => $_G['mpid'], 'id' => $id));
    return_msg(error(0, ''), '', 'ajax');
}



if($op == 'status') {
	$status = intval($_P['status']);
	$state = db_update(t_group, array('status' => $status), array('uniacid' => $_G['mpid'], 'id' => $id));
	return_msg(error(0, ''), '', 'ajax');
}

if($op == 'display'){
	
	$pageNumber = max ( 1, intval ( $_P['page'] ) );
    if ($theme['endtime']<strtotime("-90 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben') {
            return_msg('活动结束超3个月,无法查看');
        }
        $pageSize = 20;
    }elseif ($theme['endtime']<strtotime("-30 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben' && $_G['username']!=='caiwu' && $_G['username']!=='chuna') {
            return_msg('活动结束超1个月,无法查看');
        }
        $pageSize = 20;
    }else{
		$pageSize = 50;
	}
	
	if (empty($_P['createtime']['start'])){
		$starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
		$starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
	}else{
		$starttime =  strtotime($_P['createtime']['start']);
	}
	$endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']) ;
	
	
	$condition = " and 1=1 ";
	$condition = " and ord.themeid = '{$themeid}' ";
	$condition.= " and ord.addtime > '{$starttime}' and ord.addtime <= '{$endtime}' ";
	if(!isset($_P['status'])){
		$status = -1;
	}else{
		$status = intval($_P['status']);
	}
	if($status >= 0){
		$condition.= " and ord.status = '{$status}'  ";
	}
	
	$keyword = $_P['keyword'];
	if(!empty($keyword)){
		$condition.= " and (ord.username like '%{$keyword}%' or ord.mobile like '%{$keyword}%' )";
	}
	$total = db_fetchcolumn ( 'SELECT COUNT(ord.id) FROM ' . tablename ( t_group ) . " as ord
			WHERE  ord.uniacid = '{$_G['mpid']}'  {$condition} ORDER BY ord.id desc",$params);
	
	
	if(checksubmit('export_submit', true)){
		$count = $total;
		$pagesize = ceil($count/5000);
		$header = array(
		    'uid' => '会员UID', 'username' => '姓名', 'mobile' => '手机','address' => '地址',
		    'option' => '选项','code' => '兑奖码','isluck' => '是否中奖',
			'nickname' => '微信昵称','fee' => '费用',  'nickname2' => '来源', 'status' => '状态',
		    'addtime'=>'参团时间','openid'=>'Openid'
		);
		$keys = array_keys($header);
		$html = "\xEF\xBB\xBF";
		foreach ($header as $li) {
			$html .= $li . "\t ,";
		}
		$html .= "\n";
		$statustr = array("未支付","已支付","已核销");
		$luckstr = array("否","是");
		for ($j = 1; $j <= $pagesize; $j++) {
			$sql = "SELECT ord.* FROM " . tablename(t_record) . " as ord
								WHERE ord.uniacid = '{$_G['mpid']}'  " . $condition . "  ORDER BY ord.id desc limit " . ($j - 1) * 5000 . ",5000 ";
			$list = db_select($sql, $params);
			foreach ($list as $index =>$row){
				if(!empty($row['fromuid'])){
					$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['fromuid']));
					$list[$index]['nickname2'] = $fans['nickname'];
					$list[$index]['avatar2'] = $fans['avatar'];
				}
			}
			if (!empty($list)) {
				$size = ceil(count($list) / 500);
				for ($i = 0; $i < $size; $i++) {
					$buffer = array_slice($list, $i * 500, 500);
					foreach ($buffer as $row) {
	
						
						$row['status'] = $statustr[$row['status']];
						$row['isluck'] = $luckstr[$row['isluck']];
						$row['addtime']  = date('Y-m-d H:i:s',$row['addtime']);
						unset($info);
						foreach ($keys as $key) {
							$data[] = $row[$key];
						}
						$user[] = implode("\t ,", $data) . "\t ,";
						unset($data);
					}
					$html .= implode("\n", $user);
				}
			}
		}
		header("Content-type:text/csv");
		header("Content-Disposition:attachment; filename=参团数据.csv");
		echo $html;
		exit();
	}
	
	$sql = "SELECT ord.* FROM " . tablename ( t_group ) . " as ord
						WHERE  ord.uniacid = '{$_G['mpid']}'  {$condition} 
						      ORDER BY ord.id desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
	$list = db_select ( $sql,$params);
	foreach ($list as $index =>$row){
		if(!empty($row['fromuid'])){
			$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['fromuid']));
			$list[$index]['nickname2'] = $fans['nickname'];
			$list[$index]['avatar2'] = $fans['avatar'];
		}
	}
	$pager = pagination ( $total, $pageNumber, $pageSize );
}




$return_clicent = get_defined_vars();
return view('/group' , $return_clicent);
}
}